#!C:\python25\python.exe
import MySQLdb
import notes_parser
import dbi
import odbc
import re

def db_connect(dbtype = 1): # default is 1 which means mysql, 2 means carevue odbc
   if (dbtype == 1):      
       try:
           connection = MySQLdb.connect(host="localhost",user="clinnote", passwd="clinical",port=3406,db="clinnote" )
           return connection   
       except MySQLdb.OperationalError, message:
           errorMessage = "Error %d:\n%s" % (message[ 0 ], message[ 1 ] )
           print errorMessage
           try: 
              connection = MySQLdb.connect(host="localhost",user="root", passwd="",port=3306,db="clinnote" )
              return connection
           except MySQLdb.OperationalError, message:
              errorMessage = "Error %d:\n%s" % (message[ 0 ], message[ 1 ] )
              print errorMessage
  
   elif (dbtype == 2):
      try:
         connection = odbc.odbc(gicu_db)
         return connection
      except odbc.OdbcException, ex:
         print ex

def notes_middleware(result):
   p = re.compile('(<\/*\w+>)')
 #  m = p.findall(result)
 #  n = p.match(result)
 #  print n.group()
 #  print m
   result1 = p.sub("\n",result)
   return result
   
       
def notes_retrieve(mrn):
   connection = db_connect()
   results = {}
   index = 0
   cursor = connection.cursor()
   sql = "select R.CONTENT from SUBS_RPAICU as R, SUBID_MRN as M where R.SUB_ID = M.SUB_ID and M.MRN = %s" % (str(mrn))
   cursor.execute(sql)
   for content in cursor.fetchall():
      results[index] = notes_middleware(content[0])
      index = index + 1

   cursor.close
   connection.close
   return results
